package com.coldlz.mmp.ssl;

import cn.hutool.core.io.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.util.List;

public class FinalKeyPairStr extends KeyPairStr {
    private static final Logger log = LoggerFactory.getLogger(FinalKeyPairStr.class);
    private static final String NAME_PREFIX = "share-key";

    private static final FinalKeyPairStr instance;

    static {
        try {
            instance = load();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    // 加载密钥
    private static FinalKeyPairStr load() throws NoSuchAlgorithmException {
        File privateKeyFile = Util.getPrivateKeyFile(NAME_PREFIX);
        File publicKeyFile = Util.getPublicKeyFile(NAME_PREFIX);
        if (privateKeyFile.exists() && publicKeyFile.exists()) {
            List<String> pri = FileUtil.readUtf8Lines(privateKeyFile);
            List<String> pub = FileUtil.readUtf8Lines(publicKeyFile);
            KeyPairStr keyPairStr = Util.loadKeyPairStr(pri, pub);
            return new FinalKeyPairStr(keyPairStr.getKeyPair());
        } else {
            return create();
        }
    }

    private static FinalKeyPairStr create() throws NoSuchAlgorithmException {
        //log.info("开始创建 FinalKeyPairStr ");
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(CertificateContext.KEY_PAIR_ALGORITHM);
        keyPairGenerator.initialize(CertificateContext.KEY_SIZE);
        FinalKeyPairStr finalKeyPairStr = new FinalKeyPairStr(keyPairGenerator.generateKeyPair());

        Util.savePrivateKeyToFile(finalKeyPairStr.getPrivateKeyToFileStr(), NAME_PREFIX);
        Util.savePublicKeyToFile(finalKeyPairStr.getPublicKeyToFileStr(), NAME_PREFIX);
        return finalKeyPairStr;
    }

    private FinalKeyPairStr(KeyPair keyPair) {
        super(keyPair);
    }

    // 获取一个单利对象
    public static FinalKeyPairStr getInstance() {
        return instance;
    }

}
